package com.fyy.quartz.config;

import com.fyy.quartz.factory.QuartzJobFactory;
import com.fyy.quartz.listener.SimpleJobListener;
import com.fyy.quartz.listener.SimpleSchedulerListener;
import com.fyy.quartz.listener.SimpleTriggerListener;
import org.quartz.JobKey;
import org.quartz.Matcher;
import org.quartz.Scheduler;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.EverythingMatcher;
import org.quartz.impl.matchers.KeyMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.List;

/**
 * @Author fyy
 * @Description 注册调度工厂
 * @Date 2020/12/23 10:07
 */
@Configuration
public class QuartzConfig {

    @Autowired
    private QuartzJobFactory jobFactory;
    @Autowired
    private SimpleSchedulerListener simpleSchedulerListener;
    @Autowired
    private SimpleTriggerListener simpleTriggerListener;
    @Autowired
    private SimpleJobListener simpleJobListener;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        //获取配置属性
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(new ClassPathResource("quartz.yml"));
        //在quartz.yml中的属性被读取并注入后再初始化对象
        yamlPropertiesFactoryBean.afterPropertiesSet();
        //创建SchedulerFactoryBean
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(yamlPropertiesFactoryBean.getObject());
        factory.setJobFactory(jobFactory); //支持在JOB实例中注入其他的业务对象
        factory.setApplicationContextSchedulerContextKey("applicationContextKey");
        //为true时，会等待所有已经启动的quartz job结束后spring才能完全shutdown。
        factory.setWaitForJobsToCompleteOnShutdown(true);
        factory.setOverwriteExistingJobs(false); //是否覆盖己存在的Job
        factory.setStartupDelay(10); //QuartzScheduler延时启动，应用启动完后QuartzScheduler再启动
        return factory;
    }

    /**
     * @Author fyy
     * @Description 通过SchedulerFactoryBean获取Scheduler的实例
     */
    @Bean(name = "scheduler")
    public Scheduler scheduler() throws Exception{
        Scheduler scheduler = schedulerFactoryBean().getScheduler();
        //全局添加监听器
        //添加SchedulerListener监听器
        scheduler.getListenerManager().addSchedulerListener(simpleSchedulerListener);
        // 添加triggerListener，设置全局监听
        scheduler.getListenerManager().addTriggerListener(simpleTriggerListener, EverythingMatcher.allTriggers());
        // 添加JobListener, 支持带条件匹配监听器
        scheduler.getListenerManager().addJobListener(simpleJobListener, KeyMatcher.keyEquals(JobKey.jobKey("myJob", "myGroup")));
        return scheduler;
    }

}
